package com.meisiabc.app.task;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.meisiabc.app.repository.db.entity.CurriculumSchedule;
import com.meisiabc.app.repository.db.entity.Teacher;
import com.meisiabc.app.repository.db.entity.Trylistenmanage;
import com.meisiabc.app.repository.db.manager.CurriculumScheduleManager;
import com.meisiabc.app.repository.db.manager.TeacherManager;
import com.meisiabc.app.repository.db.manager.TrylistenmanageManager;
import com.meisiabc.utils.DateUtil;
import com.meisiabc.utils.DateUtils;
import com.meisiabc.utils.JwtUtil;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 *
 */
@Slf4j
@Component
public class ZoomTask {

    @Autowired
    private CurriculumScheduleManager curriculumScheduleManager;
    @Autowired
    private TeacherManager teacherManager;
    @Autowired
    private TrylistenmanageManager trylistenmanageManager;

    @Scheduled(cron = "0 0 */1 * * ?")
    public void classBeginNoticeTask() throws Exception {
        log.info("zoom 视频获取任务开始");
        String classDate = DateUtil.defalultFomrt(DateUtil.addDay(new Date(), -1));
        final List<CurriculumSchedule> curriculumSchedules = curriculumScheduleManager.getZoomIdByDate(classDate);

        log.info("课时记录为：" + JSONArray.toJSONString(curriculumSchedules));
        for (CurriculumSchedule schedule : curriculumSchedules) {
            String teacherId = schedule.getTeacherId();
            Integer id = schedule.getId();
            String class_date = DateUtil.defalultFomrt(schedule.getClassDate());
            String class_time = schedule.getClassTime();
            String class_time_end = schedule.getClassTimeEnd();
            String video = schedule.getVideo();

            Teacher teacher = teacherManager.selectByUniqueid(teacherId);

            final Date class_date_begin = DateUtils.parseDate(class_date + " " + class_time);
            final Date class_date_end = DateUtils.parseDate(class_date + " " + class_time_end);
            if (teacher != null && StringUtils.isNotBlank(teacher.getZoomid())) {

                final String token = JwtUtil.genJWTToken();
                String userId = getUserId(token, teacher.getZoomid());
                JSONObject vedio = getVedio(token, userId, classDate);
                JSONArray meetings = vedio.getJSONArray("meetings");
                log.info("video:" + meetings.toJSONString());

                for (Object meeting : meetings) {
                    JSONObject jsonMeeting = (JSONObject) meeting;
                    JSONArray recording_files = jsonMeeting.getJSONArray("recording_files");
                    for (Object file : recording_files) {
                        final JSONObject fileObject = (JSONObject) file;
                        Object file_type = fileObject.get("file_type");
                        if (file_type.equals("MP4")) {
                            String play_url = fileObject.get("play_url").toString();

                            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
                            df.setTimeZone(TimeZone.getTimeZone("UTC"));
                            Date startDate = df.parse(fileObject.get("recording_start").toString());
                            Date endDate = df.parse(fileObject.get("recording_end").toString());

                            long time = (endDate.getTime() - startDate.getTime()) / 2 + startDate.getTime();

                            final Date dateMedian = new Date(time);

                            String recording_start = DateUtil.defalultFomrt(startDate, "yyyy-MM-dd HH:mm:ss");
                            String startDateStr = DateUtil.defalultFomrt(startDate);

                            log.info("****  zoomId:" + teacher.getZoomid());
                            log.info("****  recording_median:" + DateUtil.defalultFomrt(dateMedian, "yyyy-MM-dd HH:mm:ss"));
//                            log.info("****  recording_start:" + recording_start);
                            log.info("****  class_begin:" + class_date + " " + class_time);
                            log.info("****  class_end:" + class_date + " " + class_time_end);

                            if (startDateStr.equals(class_date) && dateMedian.after(class_date_begin) && dateMedian
                                .before(class_date_end)) {

                                if (video == null) {
                                    video = play_url + "#" + recording_start;
                                    log.info("****  update video url:" + id + "  " + video);
                                    curriculumScheduleManager.updateVedio(id, video);
                                } else if (!video.contains(recording_start)) {
                                    int i = video.lastIndexOf(",");
                                    if (i == video.length() - 1) {
                                        video = video + play_url + "#" + recording_start;
                                    } else {
                                        video = video + "," + play_url + "#" + recording_start;
                                    }
                                    log.info("****  update video url:" + id + "  " + video);
                                    curriculumScheduleManager.updateVedio(id, video);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    private String getUserId(String token, String zoomId) throws Exception {
        OkHttpClient okHttpClient = new OkHttpClient();
        Response response;
        String url = "https://api.zoom.us/v2/users/" + zoomId + "?access_token=" + token;
        log.info("getUserId url :" + url);

        Request request = new Request.Builder().url(url).get().build();
        try {
            response = okHttpClient.newCall(request).execute();
            JSONObject jsonObject = JSON.parseObject(response.body().string());
            return jsonObject.get("id").toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return StringUtils.EMPTY;
    }

    private JSONObject getVedio(String token, String userId, String from) {
        OkHttpClient okHttpClient = new OkHttpClient();
        Response response;
        String url = "https://api.zoom.us/v2/users/" + userId + "/recordings?access_token=" + token + "&from=" + from;
        log.info("getVedio url :" + url);

        Request request = new Request.Builder().url(url).get().build();
        try {
            response = okHttpClient.newCall(request).execute();
            System.out.println(response.body().toString());
            return JSON.parseObject(response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private JSONObject getVedioTo(String token, String userId, String from, String to) {
        OkHttpClient okHttpClient = new OkHttpClient();
        Response response;
        String url =
            "https://api.zoom.us/v2/users/" + userId + "/recordings?access_token=" + token + "&from=" + from + "&to=" + to;
        log.info("getVedio url :" + url);

        Request request = new Request.Builder().url(url).get().build();
        try {
            response = okHttpClient.newCall(request).execute();
            System.out.println(response.body().toString());
            return JSON.parseObject(response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Scheduled(cron = "0 0 */1 * * ?")
    public void classBeginNoticeTask2() throws Exception {
        log.info("zoom 视频获取任务开始");
        final List<Trylistenmanage> trylistenmanages = trylistenmanageManager.selectAuditionTime();

        for (final Trylistenmanage trylistenmanage : trylistenmanages) {
            final String auditionTime = trylistenmanage.getAuditionTime();
            Teacher teacher = teacherManager.selectByUniqueid(trylistenmanage.getTeacherId());

            if (StringUtils.isNotBlank(auditionTime) && teacher != null && StringUtils.isNotBlank(teacher.getZoomid())) {
                try {
                    final Integer id = trylistenmanage.getId();
                    final String teacherId = trylistenmanage.getTeacherId();
                    final String classDate = auditionTime.split(",")[0].trim();
                    final String zoomid = teacher.getZoomid();

                    final String[] classTime = auditionTime.split(",")[1].trim().split(" ");
                    final String token = JwtUtil.genJWTToken();
                    String userId = getUserId(token, teacher.getZoomid());
                    JSONObject vedio = getVedioTo(token, userId, classDate, classDate);
                    JSONArray meetings = vedio.getJSONArray("meetings");
                    log.info("试听 video:" + meetings.toJSONString());

                    for (Object meeting : meetings) {
                        JSONObject jsonMeeting = (JSONObject) meeting;
                        JSONArray recording_files = jsonMeeting.getJSONArray("recording_files");
                        for (Object file : recording_files) {
                            final JSONObject fileObject = (JSONObject) file;
                            Object file_type = fileObject.get("file_type");
                            if (file_type.equals("MP4")) {
                                String play_url = fileObject.get("play_url").toString();
                                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
                                df.setTimeZone(TimeZone.getTimeZone("UTC"));
                                Date startDate = df.parse(fileObject.get("recording_start").toString());
                                Date endDate = df.parse(fileObject.get("recording_end").toString());

                                long time = (endDate.getTime() - startDate.getTime()) / 2 + startDate.getTime();
                                final Date dateMedian = new Date(time);

                                System.out.println("video mid :" + DateUtil.defalultFomrt(dateMedian, "yyyy-MM-dd HH:mm:ss"));


                                String startDateStr = DateUtil.defalultFomrt(startDate);

                                for (int i = 1; i < classTime.length; i++) {
                                    final String ti = classTime[i];
                                    final Date class_date_begin = DateUtils.parseDate(classDate + " " + ti.split("-")[0]);
                                    final Date class_date_end = DateUtils.parseDate(classDate + " " + ti.split("-")[1]);

                                    System.out.println("class begin: " + classDate + " " + ti.split("-")[0]);
                                    System.out.println("class end: " + classDate + " " + ti.split("-")[1]);
                                    if (startDateStr.equals(classDate) && dateMedian.after(class_date_begin) && dateMedian
                                        .before(class_date_end)) {
                                        String video = trylistenmanage.getVideo();
                                        String recording_start = DateUtil.defalultFomrt(startDate, "yyyy-MM-dd HH:mm:ss");
                                        if (video == null) {

                                            video = play_url + "#" + recording_start;
                                            log.info("****  update video url:" + id + "  " + video);
                                            trylistenmanageManager.updateVedio(id, video);
                                        } else if (!video.contains(recording_start)) {
                                            int i1 = video.lastIndexOf(",");
                                            if (i1 == video.length() - 1) {
                                                video = video + play_url + "#" + recording_start;
                                            } else {
                                                video = video + "," + play_url + "#" + recording_start;
                                            }
                                            log.info("****  update video url:" + id + "  " + video);
                                            trylistenmanageManager.updateVedio(id, video);
                                        }
                                    }
                                }

                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) throws Exception {
//        final ZoomTask zoomTask = new ZoomTask();
//        final String token = JwtUtil.genJWTToken();
//        String userId = zoomTask.getUserId(token, "joelle_macy@163.com");
//        JSONObject vedio = zoomTask.getVedio(token, userId, "2019-08-27");
//        System.out.println(vedio.toJSONString());

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        df.setTimeZone(TimeZone.getTimeZone("UTC"));
        Date startDate = df.parse("2019-08-27T11:02:39Z");
        String recording_start = DateUtil.defalultFomrt(startDate, "yyyy-MM-dd HH:mm:ss");
        System.out.println(recording_start);
    }
}